//
//  ViewController.m
//  TribleWar
//
//  Created by ＣＳＴ ＣＳＴ on 8/8/12.
//  Copyright (c) 2012 ＣＳＴ. All rights reserved.
//

#import "ViewController.h"
#import "PlayerController.h"
#import "RegistViewController.h"
#import "Sprite.h"
#import "GameMove.pb.h"
#import "GameUser.pb.h"
#import "NetWorkHandler.h"
#import "AppDelegate.h"
@implementation ViewController

@synthesize userAccount;
@synthesize password;
@synthesize loginBtn;
@synthesize signInBtn;
@synthesize netWorkStatusLabel;


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    [userAccount setText:[defaults objectForKey:@"userAccount"]];
    [password setText:[defaults objectForKey:@"password"]];

}

- (void)viewDidUnload
{
    [self setNetWorkStatusLabel:nil];
    [super viewDidUnload];
    gameView = nil;
    registViewController = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bricks.jpg"]];
    self.view.backgroundColor = background;
    [super viewWillAppear:animated];
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

//hide keyboard after editing
-(void)touchesEnded: (NSSet *)touches withEvent: (UIEvent *)event
{
    for (UIView* view in self.view.subviews) 
    {
        if ([view isKindOfClass:[UITextField class]])
            [view resignFirstResponder];
    }
}


- (IBAction)onLogin:(id)sender
{
    NSString *account =  [userAccount text];
    NSString *pwd = [password text];
    if (![self isValid:account password:pwd]) {
        return;
    }
    
    User *user = [[[[[User builder]setAction:ActionLogin]setAccount:account]setPassword:pwd]build];
    NSData *userData = [user data];
    
    [[AppDelegate sharedAppDelegate]->netWorkHandler_ sendData:userData Pid:PIDUser];
    gameView = [[PlayerController alloc]initWithNibName:@"PlayerController" bundle:nil];

    [AppDelegate sharedAppDelegate]->netWorkHandler_->callbackDelegate = self;
    //[self enterGame];
}



- (void)enterGame
{   
    Sprite* player = [[Sprite alloc]init];
    //init the size of the player
    player.position = CGPointMake(32, 48);
    player.curCoord = CGPointMake(32, 48);
    //player.posCoord = CGPointMake(30, 30);
    player.pid = @"1";
    
    Sprite* player1 = [[Sprite alloc]init];
    
    NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
    int curTime = [[NSNumber numberWithDouble: timeStamp]intValue];
    NSLog(@"cur time %d", curTime);
    Category category = CategoryCharacter;
    Vector *curPos = [[[[Vector builder]setX:100]setY:100]build];
    Vector *purPos = [[[[Vector builder]setX:10]setY:10]build];
    State* state = [[[[[State builder]setCurPos:curPos]setPurPos:purPos]setCurTime:curTime]build];
    Move* move = [[[[[[Move builder]setCategory:category]setState:state]setState:state]setUid:1]build];
    
    NSData* moveData = [move data];
    
    Move* move1 = [Move parseFromData:moveData];
    CGPoint curPos1 = CGPointMake(move1.state.curPos.x, move1.state.curPos.y);
    CGPoint purPos1 = CGPointMake(move1.state.purPos.x, move1.state.purPos.y);

    player1.position = curPos1;
    player1.curCoord = curPos1;
    player1.posCoord = purPos1;
    player1.pid = [NSString stringWithFormat:@"%d", move1.uid];
    
    gameView = [[PlayerController alloc]initWithNibName:@"PlayerController" bundle:nil];
    
    [gameView addPlayer:player];
    [gameView addPlayer:player1];
    [self.view addSubview:gameView.view];
}

- (IBAction)onRegist:(id)sender
{
    registViewController = [[RegistViewController alloc]initWithNibName:@"RegistViewController" bundle:nil];
    [self.view addSubview:registViewController.view];
}

- (BOOL)isValid:(NSString *)account password:(NSString *)pwd
{
    NSString * regex = @"(^[A-Za-z0-9]{3,}$)";
    NSPredicate * pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];  
    if (![pred evaluateWithObject:account]) {
        NSLog(@"account is illegal");
        return NO;
    } 
    if ([pwd length] < 6) {
        NSLog(@"pwd less than 6");
        return NO;
    }
    
    return YES;
}


-(void)loginCallback:(Ack *)ack
{
    NSLog(@"login call back");
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    if (!ack) {
        [netWorkStatusLabel setText:@"登录失败"];
        return;
    }
    if ([ack success] == NO) {
        [netWorkStatusLabel setText:[ack msg]];
        return;
    }
    [netWorkStatusLabel setText:@"登录成功"];

    gameView = [[PlayerController alloc]initWithNibName:@"PlayerController" bundle:nil];

    Sprite* player = [[Sprite alloc]init];
    //init the size of the player
    player.position = CGPointMake(32, 48);
    player.curCoord = CGPointMake(32, 48);
    //player.posCoord = CGPointMake(30, 30);
    player.pid = [defaults objectForKey:@"userAccount"];
    [gameView addPlayer:player];
    [AppDelegate sharedAppDelegate]->netWorkHandler_->callbackDelegate = gameView;
    [self.view addSubview:gameView.view];


}

- (IBAction)onPassword:(id)sender {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:[password text] forKey:@"password"];
    [defaults synchronize];    
}

- (IBAction)onSetAccount:(id)sender {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:[userAccount text] forKey:@"userAccount"];
    [defaults synchronize];    

}
@end
